<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Camera Access Example</title>
</head>
<body>

<video id="video" width="640" height="480" autoplay></video>
<button onclick="takePhoto()">Take Photo</button>
<canvas id="canvas" width="640" height="480" style="display:none;"></canvas>
<img id="photo" src="" alt="Photo will appear here..." />

<script>
// 确保DOM完全加载后再执行
document.addEventListener('DOMContentLoaded', function() {
    var video = document.getElementById('video');

    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: true })
        .then(function(stream) {
            video.srcObject = stream;
        })
        .catch(function(err0r) {
            console.log("Something went wrong!", err0r);
        });
    } else if (navigator.getUserMedia) { 
        navigator.getUserMedia({ video: true }, function(stream) {
            video.src = stream;
        }, function(err0r) {
            console.log("Something went wrong!", err0r);
        });
    } else {
        console.log("getUserMedia not supported");
    }
});

function takePhoto() {
    var video = document.getElementById('video');
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var photo = document.getElementById('photo');

    // 确保canvas尺寸与视频流匹配
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    // 将视频流绘制到canvas上
    context.drawImage(video, 0, 0, canvas.width, canvas.height);
    
    // 将canvas的内容转换为DataURL
    console.log(canvas.toDataURL(),'canvas.toDataURL()')
    photo.src = canvas.toDataURL();
}
</script>
</body>
</html>